package com.itheiya.service.impl;


import com.alibaba.fastjson.JSON;
import com.hmall.common.client.FeignItemClient;
import com.hmall.common.dto.PageDTO;

import com.hmall.common.pojo.Item;
import com.itheiya.mq.ItemListener;
import com.itheiya.pojo.ItemDoc;
import com.itheiya.pojo.RequestParams;
import com.itheiya.service.ItermIdexService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItermldexServiceImpl implements ItermIdexService {

    @Autowired
    private RestHighLevelClient client;


    @Autowired

    private FeignItemClient itemClient;


    @Override
    public List<String> findSuggestion(String key) {
        // 创建请求对象

        try {

            SearchRequest request = new SearchRequest("item");

            request.source().suggest(
                    new SuggestBuilder().addSuggestion(
                            "MySuggestion",
                            SuggestBuilders
                                    .completionSuggestion("suggestion")
                                    .prefix(key)
                                    .skipDuplicates(true)
                                    .size(10)
                    ));

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            List<String> list = new ArrayList<>();
            //解析结果
            Suggest suggest = response.getSuggest();

            //根据聚合名称得到聚合结果
            CompletionSuggestion cs = suggest.getSuggestion("MySuggestion");
            // 获取options 并且遍历
            List<CompletionSuggestion.Entry.Option> options = cs.getOptions();

            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                list.add(s);
            }

            return list;

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

    }

    @Override
    public Map<String, List<String>> searchItemFilters(RequestParams requestParams) {
        try {
            SearchRequest request = new SearchRequest("item");
//            request.source().size(0);

            SearchSourceBuilder source = request.source();
            //聚合条件
            booleanQuery(source,requestParams);
            buildAggregation(source);

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();

            List<String> brandList = getAggByName(aggregations, "brandAgg");
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
//            List<String> sortByList = getAggByName(aggregations, "sortByAgg");

            result.put("brand", brandList);
            result.put("category", categoryList);
//            result.put("sortBy", sortByList);

            return result;


        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

    }


    //综合条件过滤
    @Override
    public PageDTO<ItemDoc> multipleTermFilter(RequestParams Params) {
        SearchRequest request = new SearchRequest("item");

        SearchSourceBuilder source = request.source();
        Integer page = Params.getPage();
        Integer size = Params.getSize();

        source.from((page - 1) * size);
        source.size(size);

        booleanQuery(source, Params);

        try {

            //调用client执行
            List<ItemDoc> list = new ArrayList<>();
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            //获取查询总数
            long value = hits.getTotalHits().value;

            for (SearchHit hit : hits) {
                String doJson = hit.getSourceAsString();

                ItemDoc itemDoc = JSON.parseObject(doJson, ItemDoc.class);

                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    HighlightField highlightField = highlightFields.get("name");
                    if (highlightField != null) {
                        String name = highlightField.getFragments()[0].string();
                        itemDoc.setName(name);
                    }
                }
                list.add(itemDoc);
            }
            PageDTO<ItemDoc> pageDTO = new PageDTO<>();
            pageDTO.setList(list);
            pageDTO.setTotal(value);
            return pageDTO;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();

        }

    }

    @Override
    public void deleteById(Long id) {
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("item",id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public void insertById(Long id) {
        try {
            // 0.根据id查询酒店数据
            Item item = itemClient.selectItemById(Long.valueOf(id));
            // 转换为文档类型
            ItemDoc itemDoc = new ItemDoc(item);

            // 1.准备Request对象
            IndexRequest request = new IndexRequest("item");
            request.id(String.valueOf(item.getId()));
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    // 聚合过滤
    private void booleanQuery(SearchSourceBuilder source, RequestParams params) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        String Key = params.getKey();
        if (StringUtils.isNotBlank(Key)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", Key));
            source.highlighter(new HighlightBuilder().field("name")
                    .requireFieldMatch(false));

        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }

        // 构建category term搜索
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", category));
        }

        // 构建品牌 term搜索
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }


        Long minPrice = params.getMinPrice();
        Long maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQueryBuilder.filter(
                    QueryBuilders.rangeQuery(
                            "price").gte(minPrice*100).lt(maxPrice*100));

        }


        /**
         *排序根据价格
         */
        String sortBy = params.getSortBy();
        if (StringUtils.isNotBlank(sortBy)) {
            if (sortBy.equals("sold")) {
                source.sort(sortBy, SortOrder.DESC);
            }
            if (sortBy.equals("price")) {
                source.sort(sortBy, SortOrder.ASC);
            }
        }

        // 算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                // 原始查询,相关算分查询
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //其中一个function score 元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                //算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                });
        source.query(functionScoreQuery);
    }


    private List<String> getAggByName(Aggregations aggregations, String brandAgg) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(brandAgg);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }


    //聚合
    private void buildAggregation(SearchSourceBuilder source) {
        source.aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(20)
        );
        source.aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(20)
        );
//        source.aggregation(AggregationBuilders
//                .terms("sortByAgg")
//                .field("sortBy")
//                .size(20)
//        );


    }
}
